/**
 * 项目对话框状态管理
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { 
  ProjectCreate, 
  ProjectResponse, 
  ProjectPriority, 
  ProjectType 
} from '@/api/project'
import type { ProjectStatus } from '@/types/project'
import { 
  createProject, 
  updateProject, 
  getProject 
} from '@/api/project'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ResponseParser } from '@/utils/responseParser'
import { ErrorType, type ApiResponse } from '@/types/api'

export interface ProjectFormData extends ProjectCreate {
  id?: string
}

export interface ProjectDialogState {
  isOpen: boolean
  loading: boolean
  mode: 'create' | 'edit'
  currentStep: number
  formData: ProjectFormData
  errors: Record<string, string>
  originalData?: ProjectResponse
}

export const useProjectDialogStore = defineStore('projectDialog', () => {
  // 状态
  const state = ref<ProjectDialogState>({
    isOpen: false,
    loading: false,
    mode: 'create',
    currentStep: 0,
    formData: {
      name: '',
      description: '',
      project_type: 'web' as ProjectType, // 修复：使用字符串字面量
      status: '' as ProjectStatus, // 动态获取默认状态
      priority: 'medium' as ProjectPriority, // 修复：使用字符串字面量
      start_date: '',
      end_date: '',
      budget: 0,
      tags: [],
      is_public: false,
      repository_url: '',
      documentation_url: ''
    },
    errors: {},
    originalData: undefined
  })

  // 计算属性
  const isOpen = computed(() => state.value.isOpen)
  const loading = computed(() => state.value.loading)
  const mode = computed(() => state.value.mode)
  const currentStep = computed(() => state.value.currentStep)
  const formData = computed(() => state.value.formData)
  const errors = computed(() => state.value.errors)
  const originalData = computed(() => state.value.originalData)

  // 表单步骤配置
  const steps = [
    {
      id: 'basic',
      title: '基本信息',
      description: '设置项目的基本信息'
    },
    {
      id: 'details',
      title: '详细配置',
      description: '配置项目的详细设置'
    },
    {
      id: 'confirm',
      title: '确认信息',
      description: '确认项目信息并创建'
    }
  ]

  // 状态选项 - 使用动态状态管理
  // 注意：statusOptions 现在通过 useProjectStates composable 在组件中获取
  // 这里保留为空数组，由组件调用 useProjectStates() 获取
  const statusOptions = ref<Array<{ value: ProjectStatus; label: string; type: string; description: string }>>([])

  // 优先级选项
  const priorityOptions = [
    { value: 'low' as ProjectPriority, label: '低', type: 'info', description: '低优先级' },
    { value: 'medium' as ProjectPriority, label: '中', type: 'warning', description: '中等优先级' },
    { value: 'high' as ProjectPriority, label: '高', type: 'danger', description: '高优先级' },
    { value: 'critical' as ProjectPriority, label: '严重', type: 'danger', description: '严重优先级' }
  ]

  // 项目类型选项
  const typeOptions = [
    { value: 'web' as ProjectType, label: 'Web应用', description: 'Web应用程序项目' },
    { value: 'mobile' as ProjectType, label: '移动应用', description: '移动应用程序项目' },
    { value: 'desktop' as ProjectType, label: '桌面应用', description: '桌面应用程序项目' },
    { value: 'api' as ProjectType, label: 'API服务', description: 'API服务项目' },
    { value: 'infrastructure' as ProjectType, label: '基础设施', description: '基础设施项目' },
    { value: 'research' as ProjectType, label: '研究项目', description: '研究和开发项目' },
    { value: 'maintenance' as ProjectType, label: '维护项目', description: '维护和支持项目' },
    { value: 'other' as ProjectType, label: '其他', description: '其他类型项目' }
  ]

  // 重置表单数据
  const resetFormData = () => {
    state.value.formData = {
      name: '',
      description: '',
      project_type: 'web' as ProjectType,
      status: '' as ProjectStatus, // 动态获取默认状态
      priority: 'medium' as ProjectPriority,
      start_date: '',
      end_date: '',
      budget: 0,
      tags: [],
      is_public: false,
      repository_url: '',
      documentation_url: ''
    }
    state.value.errors = {}
    state.value.currentStep = 0
    state.value.originalData = undefined
  }

  // 打开创建对话框
  const openCreateDialog = () => {
    resetFormData()
    state.value.mode = 'create'
    state.value.isOpen = true
  }

  // 打开编辑对话框
  const openEditDialog = async (projectId: string) => {
    try {
      state.value.loading = true
      const response = await getProject(projectId)
      
      if (response.code === 200 && response.data) {
        const project = response.data
        state.value.formData = {
          id: project.id,
          name: project.name,
          description: project.description || '',
          project_type: project.project_type,
          status: project.status,
          priority: project.priority,
          start_date: project.start_date || '',
          end_date: project.end_date || '',
          budget: project.budget || 0,
          tags: project.tags || [],
          is_public: project.is_public,
          repository_url: project.repository_url || '',
          documentation_url: project.documentation_url || ''
        }
        state.value.originalData = project
        state.value.mode = 'edit'
        state.value.isOpen = true
        state.value.errors = {}
        state.value.currentStep = 0
      } else {
        ElMessage.error('获取项目信息失败')
      }
    } catch (error) {
      console.error('获取项目信息失败:', error)
      ElMessage.error('获取项目信息失败')
    } finally {
      state.value.loading = false
    }
  }

  // 关闭对话框
  const closeDialog = () => {
    state.value.isOpen = false
    setTimeout(() => {
      resetFormData()
    }, 300) // 等待动画完成后重置数据
  }

  // 更新表单数据
  const updateFormData = (data: Partial<ProjectFormData>) => {
    state.value.formData = { ...state.value.formData, ...data }
  }

  // 设置错误信息
  const setErrors = (errors: Record<string, string>) => {
    state.value.errors = errors
  }

  // 清除错误信息
  const clearErrors = () => {
    state.value.errors = {}
  }

  // 设置当前步骤
  const setCurrentStep = (step: number) => {
    state.value.currentStep = step
  }

  // 验证表单数据
  const validateForm = (step?: number): boolean => {
    const errors: Record<string, string> = {}
    const currentStepIndex = step !== undefined ? step : state.value.currentStep

    // 基本信息验证
    if (currentStepIndex === 0) {
      if (!state.value.formData.name.trim()) {
        errors.name = '项目名称不能为空'
      } else if (state.value.formData.name.length > 100) {
        errors.name = '项目名称不能超过100个字符'
      }

      if (state.value.formData.description && state.value.formData.description.length > 1000) {
        errors.description = '项目描述不能超过1000个字符'
      }
    }

    // 详细配置验证
    if (currentStepIndex === 1) {
      if (state.value.formData.start_date && state.value.formData.end_date) {
        const startDate = new Date(state.value.formData.start_date)
        const endDate = new Date(state.value.formData.end_date)
        if (startDate >= endDate) {
          errors.end_date = '结束日期必须晚于开始日期'
        }
      }

      if (state.value.formData.budget && state.value.formData.budget < 0) {
        errors.budget = '预算不能为负数'
      }

      if (state.value.formData.repository_url && !isValidUrl(state.value.formData.repository_url)) {
        errors.repository_url = '请输入有效的仓库URL'
      }

      if (state.value.formData.documentation_url && !isValidUrl(state.value.formData.documentation_url)) {
        errors.documentation_url = '请输入有效的文档URL'
      }
    }

    state.value.errors = errors
    return Object.keys(errors).length === 0
  }

  // URL验证辅助函数
  const isValidUrl = (url: string): boolean => {
    try {
      new URL(url)
      return true
    } catch {
      return false
    }
  }

  // 提交表单
  const submitForm = async (): Promise<boolean> => {
    if (!validateForm()) {
      return false
    }

    try {
      state.value.loading = true
      
      const formData = { ...state.value.formData }
      delete formData.id // 移除id字段，避免传递给API

      let response: ApiResponse<ProjectResponse>
      if (state.value.mode === 'create') {
        response = await createProject(formData)
      } else {
        response = await updateProject(state.value.formData.id!, formData)
      }

      // 解析响应
      const parsed = ResponseParser.parseResponse(response)
      
      if (parsed.success || response.code === 200) {
        ElMessage.success(state.value.mode === 'create' ? '项目创建成功' : '项目更新成功')
        closeDialog()
        return true
      } else {
        // 检查是否为权限错误
        const errorData = response?.error || response?.data?.error
        const errorType = errorData?.type
        const statusCode = response?.code
        
        // 权限错误（403 或 PERMISSION_ERROR）
        if (statusCode === 403 || errorType === ErrorType.PERMISSION_ERROR || errorType === 'PERMISSION_ERROR') {
          const friendlyMessage = state.value.mode === 'create' 
            ? '您没有权限创建项目。请联系管理员获取相应权限。'
            : '您没有权限编辑此项目。只有项目负责人或管理员可以修改项目信息。如需编辑，请联系项目负责人或系统管理员。'
          
          ElMessageBox.alert(friendlyMessage, '权限不足', {
            confirmButtonText: '我知道了',
            type: 'warning',
            showClose: false
          })
          return false
        }
        
        // 其他错误
        const errorMessage = parsed.message || response.message || '操作失败'
        ElMessage.error(errorMessage)
        return false
      }
    } catch (error: any) {
      console.error('提交表单失败:', error)
      
      // 检查是否为权限错误
      const errorResponse = error?.response?.data || error?.response || error
      const errorType = errorResponse?.error?.type || errorResponse?.error_type
      const statusCode = error?.response?.status || errorResponse?.code || errorResponse?.status
      
      // 权限错误（403 或 PERMISSION_ERROR）
      if (statusCode === 403 || errorType === ErrorType.PERMISSION_ERROR || errorType === 'PERMISSION_ERROR') {
        const friendlyMessage = state.value.mode === 'create' 
          ? '您没有权限创建项目。请联系管理员获取相应权限。'
          : '您没有权限编辑此项目。只有项目负责人或管理员可以修改项目信息。如需编辑，请联系项目负责人或系统管理员。'
        
        ElMessageBox.alert(friendlyMessage, '权限不足', {
          confirmButtonText: '我知道了',
          type: 'warning',
          showClose: false
        })
        return false
      }
      
      // 处理验证错误
      if (error.response?.status === 422 && error.response?.data?.detail) {
        const validationErrors: Record<string, string> = {}
        error.response.data.detail.forEach((err: any) => {
          const field = err.loc[err.loc.length - 1]
          validationErrors[field] = err.msg
        })
        setErrors(validationErrors)
      } else {
        const errorMessage = ResponseParser.extractMessage(error) || error.message || '操作失败'
        ElMessage.error(errorMessage)
      }
      
      return false
    } finally {
      state.value.loading = false
    }
  }

  return {
    // 状态
    state: computed(() => state.value),
    isOpen,
    loading,
    mode,
    currentStep,
    formData,
    errors,
    originalData,
    
    // 配置
    steps,
    statusOptions,
    priorityOptions,
    typeOptions,
    
    // 方法
    openCreateDialog,
    openEditDialog,
    closeDialog,
    updateFormData,
    setErrors,
    clearErrors,
    setCurrentStep,
    validateForm,
    submitForm,
    resetFormData
  }
})